<template>
  <div class="volunteer-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="志愿者姓名">
          <el-input v-model="searchForm.name" placeholder="请输入志愿者姓名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增志愿者</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="volunteerList" border stripe v-loading="tableLoading">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            {{ row.gender === 0 ? '男' : row.gender === 1 ? '女' : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="totalHours" label="服务时长" width="100">
          <template #default="{ row }">
            {{ row.volunteerHours }} 小时
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="handleDetail(row)">详情</el-button>
            <el-button link type="primary" @click="handleResetPwd(row)">重置密码</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 志愿者表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增志愿者' : '编辑志愿者'"
      width="600px"
    >
      <el-form
        ref="volunteerFormRef"
        :model="volunteerForm"
        :rules="volunteerRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="volunteerForm.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="volunteerForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="volunteerForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="volunteerForm.email" />
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="volunteerForm.region"
            :options="regionOptions"
            placeholder="请选择地区"
          />
        </el-form-item>
        <el-form-item label="个人简介" prop="skills">
          <el-input
            v-model="volunteerForm.skills"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="志愿者详情"
      width="800px"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="姓名">{{ currentDetail.name }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ currentDetail.gender === 0 ? '男' : currentDetail.gender === 1 ? '女' : '' }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ currentDetail.phone }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ currentDetail.email }}</el-descriptions-item>
            <el-descriptions-item label="出生日期">{{ currentDetail.birthDate }}</el-descriptions-item>
            <el-descriptions-item label="所在地区">{{ currentDetail.region }}</el-descriptions-item>
            <el-descriptions-item label="个人简介" :span="2">{{ currentDetail.skills }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="服务记录" name="service">
          <el-table :data="serviceRecords" border stripe style="width: 100%;">
            <el-table-column prop="activityTitle" label="项目名称">
              <template #default="{ row }">
                {{ row.activityTitle || '其他服务' }}
              </template>
            </el-table-column>
            <el-table-column prop="serviceLocation" label="服务地点" />
            <el-table-column prop="serviceHours" label="服务时长">
              <template #default="{ row }">
                {{ row.serviceHours }} 小时
              </template>
            </el-table-column>
            <el-table-column prop="serviceDate" label="服务日期" width="180">
              <template #default="{ row }">
                {{ formatDate(row.serviceDate) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag :type="getServiceStatusType(row.status)">
                  {{ getServiceStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="服务描述" show-overflow-tooltip />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getVolunteerList, getVolunteerDetail, addVolunteer, updateVolunteer, deleteVolunteer, changeVolunteerStatus, resetVolunteerPassword, getVolunteerServiceRecords } from '@/api/volunteer'

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  status: '',
  dateRange: []
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 志愿者列表
const volunteerList = ref([])
const tableLoading = ref(false)
const dataInitialized = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const detailDialogVisible = ref(false)
const activeTab = ref('basic')
const currentDetail = ref({})
const volunteerFormRef = ref(null)

// 志愿者表单
const volunteerForm = reactive({
  name: '',
  gender: 0,
  phone: '',
  email: '',
  birthday: '',
  region: [],
  skills: ''
})

// 表单校验规则
const volunteerRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 地区选项
const regionOptions = [
  {
    value: 'guangdong',
    label: '广东省',
    children: [
      {
        value: 'shenzhen',
        label: '深圳市',
        children: [
          { value: 'futian', label: '福田区' },
          { value: 'nanshan', label: '南山区' }
        ]
      }
    ]
  }
  // ... 更多地区数据
]

// 服务记录
const serviceRecords = ref([])

// 获取服务状态类型
const getServiceStatusType = (status) => {
  const types = {
    0: 'info',    // 待开始
    1: 'success', // 已完成
    2: 'warning'  // 进行中
  }
  return types[status] || 'info'
}

// 获取服务状态文本
const getServiceStatusText = (status) => {
  const texts = {
    0: '待开始',
    1: '已完成',
    2: '进行中'
  }
  return texts[status] || '未知'
}

// 获取志愿者列表
const loadVolunteerList = async () => {
  tableLoading.value = true
  dataInitialized.value = false
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name || undefined,
      phone: searchForm.phone || undefined,
      status: searchForm.status || undefined,
      startTime: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endTime: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined
    }
    
    const res = await getVolunteerList(params)
    if (res && res.code === 200) {
      volunteerList.value = res.data.list
      total.value = res.data.total
      
      setTimeout(() => {
        dataInitialized.value = true
      }, 100)
    } else {
      ElMessage.error(res?.message || '获取志愿者列表失败')
    }
  } catch (error) {
    console.error('加载志愿者列表出错:', error)
    ElMessage.error('获取志愿者列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 查看详情
const handleDetail = async (row) => {
  try {
    const res = await getVolunteerDetail(row.id)
    if (res && res.code === 200) {
      currentDetail.value = res.data
      
      // 获取服务记录
      const serviceRes = await getVolunteerServiceRecords(row.id)
      if (serviceRes && serviceRes.code === 200) {
        serviceRecords.value = serviceRes.data.list || []
      }
      
      nextTick(() => {
        detailDialogVisible.value = true
        activeTab.value = 'basic'
      })
    } else {
      ElMessage.error(res?.message || '获取志愿者详情失败')
    }
  } catch (error) {
    console.error('获取志愿者详情出错:', error)
    ElMessage.error('获取志愿者详情失败')
  }
}

// 处理状态修改
const handleStatusChange = async (row) => {
  if (!dataInitialized.value) return
  
  try {
    const res = await changeVolunteerStatus(row.id, row.status)
    if (res && res.code === 200) {
      const status = row.status === 'active' ? '启用' : '禁用'
      ElMessage.success(`已${status}该志愿者`)
    } else {
      // 如果失败，恢复原来的状态
      row.status = row.status === 'active' ? 'disabled' : 'active'
      ElMessage.error(res?.message || '修改状态失败')
    }
  } catch (error) {
    // 如果发生错误，恢复原来的状态
    row.status = row.status === 'active' ? 'disabled' : 'active'
    console.error('修改志愿者状态出错:', error)
    ElMessage.error('修改状态失败，请重试')
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该志愿者？删除后将无法恢复',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteVolunteer(row.id)
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        loadVolunteerList()
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      console.error('删除志愿者出错:', error)
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => {})
}

// 编辑志愿者
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(volunteerForm).forEach(key => {
    if (key in row) {
      volunteerForm[key] = row[key]
    }
  })
  volunteerForm.id = row.id
  dialogVisible.value = true
}

// 新增志愿者
const handleAdd = () => {
  dialogType.value = 'add'
  // 重置表单
  Object.keys(volunteerForm).forEach(key => {
    volunteerForm[key] = key === 'gender' ? 0 : ''
  })
  delete volunteerForm.id
  dialogVisible.value = true
}

// 表单提交
const handleSubmit = async () => {
  volunteerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (dialogType.value === 'add') {
          res = await addVolunteer(volunteerForm)
        } else {
          res = await updateVolunteer(volunteerForm.id, volunteerForm)
        }
        
        if (res && res.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          loadVolunteerList()
        } else {
          ElMessage.error(res?.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        console.error('提交志愿者表单出错:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 重置密码
const handleResetPwd = (row) => {
  ElMessageBox.confirm(
    '确认重置该志愿者的密码？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await resetVolunteerPassword(row.id)
      if (res && res.code === 200) {
        ElMessage.success(`密码已重置为${res.data || '默认密码'}`)
      } else {
        ElMessage.error(res?.message || '重置密码失败')
      }
    } catch (error) {
      console.error('重置密码出错:', error)
      ElMessage.error('重置密码失败，请重试')
    }
  }).catch(() => {})
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadVolunteerList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  currentPage.value = 1
  loadVolunteerList()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadVolunteerList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadVolunteerList()
}

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
}

// 页面加载时获取志愿者列表
onMounted(() => {
  loadVolunteerList()
})
</script>

<style scoped lang="scss">
.volunteer-management {
  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 